﻿using Common;
using Domain;
using Domain.Repositories;
using Infrastructure;
using MediatR;
using Microsoft.Extensions.Logging;

namespace Application.User
{
    public class CreateUserCommandHandler : IRequestHandler<CreateUserCommand, long>
    {
        private readonly IUserRepository _userRepository;
        private readonly SnowFlake _snowFlake;
        private readonly IMediator _mediator;

        public CreateUserCommandHandler(IUserRepository userRepository, SnowFlake snowFlake, IMediator mediator)
        {
            _userRepository = userRepository;
            _snowFlake = snowFlake;
            _mediator = mediator;
        }

        public async Task<long> Handle(CreateUserCommand request, CancellationToken cancellationToken)
        {
            var exists = await _userRepository.GetAsync(d => d.LoginName == request.LoginName);
            if (exists != null)
                return default;

            var user = await _userRepository.AddAsync(new Domain.Entities.User
            {
                Id = _snowFlake.NextId(),
                Attr = request.Attr,
                Status = Domain.Entities.UserStatus.Enable,
                Email = request.Email,
                ExtInfo = request.ExtInfo,
                Password = HashHelper.ComputeMD5Hash(request.Password + ConstKeyNames.MD5Salt),
                RealName = request.RealName,
                LoginName = request.LoginName,
                Phone = request.Phone,
                CreateTime = DateTime.Now,
                UpdateTime = DateTime.Now
            });

            _mediator.Publish(request);

            return user.Id;
        }
    }

    public class EmailNotificationHandler(ILogger<EmailNotificationHandler> logger)
        : INotificationHandler<CreateUserCommand>
    {
        public async Task Handle(CreateUserCommand notification, CancellationToken cancellationToken)
        {
            logger.LogInformation("发送邮件 {loginName} {email}", notification.LoginName, notification.Email);

            await Task.Delay(3000, cancellationToken);
        }
    }

    public class SmsNotificationHandler(ILogger<SmsNotificationHandler> logger)
        : INotificationHandler<CreateUserCommand>
    {
        public async Task Handle(CreateUserCommand notification, CancellationToken cancellationToken)
        {
            logger.LogInformation("发送短信 {loginName} {phone}", notification.LoginName, notification.Phone);

            await Task.Delay(3000, cancellationToken);
        }
    }
}